#include <gflags/gflags.h>
#include <glog/logging.h>
#include <algorithm>
#include <vector>
#include "base/file.h"
#include <sstream>

DEFINE_string(log, "", "log file to statistic");
DEFINE_string(filter, "", "filter flag: such as: [LoadImage]|[boost_det]");
DEFINE_string(start, "Time Cost: ", "time flag");
DEFINE_string(end, "ms", "time flag");
DEFINE_string(log_flag, "", "log_flag");
DEFINE_int32(ignore_count_start, 0, "ignore count start");
DEFINE_int32(ignore_count_end, 0, "ignore count end");

int main(int argc, char** argv) {
  google::ParseCommandLineFlags(&argc, &argv, false);
  google::InitGoogleLogging(argv[0]);

  if (FLAGS_log.empty()) {
    LOG(ERROR) << "log file must not empty!";
    return -1;
  }

  if (FLAGS_filter.empty()) {
    LOG(ERROR) << "filter flag must not empty!";
    return -1;
  }

  std::list<std::string> log_list;
  if (!File::ReadFileToList(FLAGS_log, &log_list)) {
    LOG(ERROR) << "read log file error: " << FLAGS_log;
    return -1;
  }

  std::list<double> time_list;
  for (const auto& log : log_list) {
    std::size_t index = log.find(FLAGS_filter);
    if (index == std::string::npos) {
      // LOG(WARNING) << "filter not found";
      continue;
    }

    std::size_t index1 = log.find(FLAGS_start);
    if (index1 == std::string::npos) {
      // LOG(WARNING) << "start not found";
      continue;
    }

    std::size_t start_flag_length = FLAGS_start.length();
    std::size_t index2 = log.find(FLAGS_end, index1 + start_flag_length);
    if (index2 == std::string::npos) {
      // LOG(WARNING) << "end not found";
      continue;
    }

    std::string data = log.substr(index1 + start_flag_length, index2 - index1 - start_flag_length);
    if (!data.empty()) {
      time_list.push_back(::atof(data.c_str()));
    }
  }
 
  double total_time = 0.0f;
  double average_time = 0.0f;
  int index = 0;
  int total_number = 0;
  for (const auto& data : time_list) {
    if (index < FLAGS_ignore_count_start) {
      index++;
      continue;
    }
    if (index >= time_list.size() - FLAGS_ignore_count_end) break;
    total_time += data;
    index++;
    total_number++;
  }

  LOG(INFO) << FLAGS_log_flag
            << "total time: " << total_time << ", total number: " << total_number
            << ", average time: " << total_time / total_number;
}
